<!--
 * @Author: 常安民 changanmin1@crdigital.com.cn
 * @Date: 2024-05-11 14:09:19
 * @LastEditors: 常安民 changanmin1@crdigital.com.cn
 * @LastEditTime: 2024-08-09 20:38:04
 * @FilePath: /console-web/src/views/trip/manager/runtrip/openCard.vue
 * @Description: 
 * @email:anmin@foxmail.com
 * Copyright (c) 2024 by 华润数科控股有限公司/常安民, All Rights Reserved. 
-->
<template>
  <!-- 页面-员工开卡管理 -->
  <div class="innerPageTable-out-flex">
    <!-- 搜索区域 -->
    <SelfAdaption>
      <Form
        :model="searchForm"
        ref="searchForm"
        slot="adaption-bar"
        label-position="top"
        class="ivu-form-no-margin-bottom"
        inline
      >
        <template>
          <FormItem prop="tenantCode" label="租户" v-if="isPlatformAdmin">
            <Select label-in-value filterable v-model="searchForm.tenantCode" style="width: 100%" clearable>
              <Option v-for="tenant in tenantList" :value="tenant.tenantCode" :key="tenant.id">
                {{ tenant.tenantName }} - {{ tenant.tenantCode }}
              </Option>
            </Select>
          </FormItem>
          <FormItem prop="travelStandardName" label="润出行账号">
            <Input
              type="text"
              :maxlength="30"
              v-model.trim="searchForm['travelStandardName']"
              placeholder="请输入润出行账号"
              clearable
              @on-enter="search"
            ></Input>
          </FormItem>

          <FormItem prop="travelStandardName" label="员工号">
            <Input
              type="text"
              :maxlength="30"
              v-model.trim="searchForm['travelStandardName']"
              placeholder="请输入员工号"
              clearable
              @on-enter="search"
            ></Input>
          </FormItem>
          <FormItem prop="travelStandardName" label="姓名">
            <Input
              type="text"
              :maxlength="30"
              v-model.trim="searchForm['travelStandardName']"
              placeholder="请输入姓名"
              clearable
              @on-enter="search"
            ></Input>
          </FormItem>
          <FormItem prop="travelStandardName" label="手机号">
            <Input
              type="text"
              :maxlength="30"
              v-model.trim="searchForm['travelStandardName']"
              placeholder="请输入手机号"
              clearable
              @on-enter="search"
            ></Input>
          </FormItem>
          <FormItem prop="travelStandardName" label="证件号">
            <Input
              type="text"
              :maxlength="30"
              v-model.trim="searchForm['travelStandardName']"
              placeholder="请输入证件号"
              clearable
              @on-enter="search"
            ></Input>
          </FormItem>
          <!-- 状态 -->
          <FormItem prop="enabled" :label="$t('common.status')">
            <Select
              style="width: 100%;"
              v-model.trim="searchForm.enabled"
              :placeholder="$t('common.warning.selectStatus')"
              clearable
            >
              <Option v-for="(item, index) in searchStatusList" :value="item.vsiKey" :key="index">{{
                item.vsiValue
              }}</Option>
            </Select>
          </FormItem>
          <!-- 查询\重置按钮 -->
          <FormItem prop="button" class="search-solt-btn">
            <RPButton optType="search" @click="search" />
            <RPButton optType="reset" @click="reset" />
          </FormItem>
        </template>
      </Form>
    </SelfAdaption>
    <InnerPageTable ref="searchTable" :config="tableConfig" v-if="this.userRolePermission || this.appRolePermission">
      <div slot="table-bar">
        <!-- <RPButton optType="create" @click="onOpenAddPage" /> -->
        <!-- v-permission="'ROLE_INDEX'" -->
      </div>
    </InnerPageTable>
  </div>
</template>

<script>
import { searchAppListByTenantCode } from '@/api/applicationApi.js'
import tenantAPI from '@/api/tenantApi.js'
import valueSetAPI from '@/api/valueSetAPI.js'
import { CoreModuleName } from '@/const.js'
import { apiTripAccountBatchOperate, apiTripAccountQueryPage } from '@api/trip/opencard/tripOpenCard.js'
import debounce from 'lodash/debounce'
import { mapGetters } from 'vuex'
import consta from './const.js'
export default {
  name: 'config-trip-open-card',
  data() {
    return { 
      title: '润出行账号',
      searchStatusList: [], //状态下拉框数据
      tenantList: [],
      searchForm: {
        tenantCode: '', // 所属租户
        crtripId: '', //润出行账号ID
        // 姓名 (surName)
        surName: '',
        // 手机号 (Phone Number)
        mobile: '',
        /** 证件类型 
          1:身份证 
          2:公务护照 
          3:普通护照 
          4:港澳通行证 
          5:台胞证 
          6:回乡证 
          7:军人证
          8:海员证 
          9:其他 
          10:台湾通行证 
          11.外国永久居留证 
          12  港澳台居民居住证 */
        identityType: '',
        // 证件号
        identityId: '',
        // 差标职级名称 (Position Title)
        positionLevelName: '',
        baseCity: '', // base城市
        // baseCityName: '', // base城市名称
        /**
         *  员工类型 
            0:员工
            1:因公客人
            2:因私客人
         */
        employeeType: '',
        // 员工号
        employeeId: '',
        // 在职状态 (workingState)
        workingState: '',
        // 开通日期 (Start Date)
        createTime: '',
        // 更新日期 (Update Date)
        updateTime: ''
      }
    }
  },
  computed: {
    ...mapGetters(['isPlatformAdmin']),
    tableConfig() {
      return {
        border: true,
        loadDataFn: this.queryListByPage,
        columnsFn: () => {
          let columns = [
            {
              type: 'selection',
              width: 50,
              align: 'center'
            },
            {
              title: '所属租户',
              key: 'tenantCode', 
              width: 200,  
              resizable: true,
              sortable: 'custom',
              render: (h, params) => {
                let title = ''
                if(this.tenantByName[params.row.tenantCode]){
                  title = this.tenantByName[params.row.tenantCode] + `(${params.row['tenantCode']})`
                }
                else{
                  title = `${params.row['tenantCode']}`
                }
                return h(
                  'div',
                  {
                    attrs: {
                      class: 'ivu-table-cell ivu-table-cell-ellipsis',
                      title: title
                    }
                  },
                  title
                )
              }
            },
            {
              title: 'CRTID',
              key: 'crtripId',
              width: 100, 
              resizable: true,
              sortable: 'custom',
              render: (h, params) => {
                let title = params.row['crtripId']
                return h(
                  'div',
                  {
                    attrs: {
                      class: 'ivu-table-cell ivu-table-cell-ellipsis',
                      title: title
                    }
                  },
                  title
                )
              }
            },
            {
              title: '姓名',
              key: 'surName',
              align: 'center',
              resizable: true,
              sortable: 'custom',
              render: (h, params) => {
                let title = params.row.surName
                return h(
                  'div',
                  {
                    attrs: {
                      class: 'ivu-table-cell ivu-table-cell-ellipsis',
                      title: title
                    }
                  },
                  title
                )
              }
            },
            {
              title: '手机号',
              key: 'mobile',
              align: 'center',
              resizable: true,
              sortable: 'custom',
              render: (h, params) => {
                let title = params.row.mobile
                return h(
                  'div',
                  {
                    attrs: {
                      class: 'ivu-table-cell ivu-table-cell-ellipsis',
                      title: title
                    }
                  },
                  title
                )
              }
            },
            {
              title: '证件类型',
              key: 'identityType',
              align: 'left',
              width: 100,
              resizable: true,
              sortable: 'custom',
              render: (h, params) => {
                let val = +params.row['identityType'];
                let title = '';
                if(val && val > 0){
                  val = val-1;
                  title = this.IdentityTypeArray[val];  
                } 
                return h(
                  'div',
                  {
                    attrs: {
                      class: 'ivu-table-cell ivu-table-cell-ellipsis',
                      title: title
                    }
                  },
                  title
                )
              }
            },
            {
              title: '证件号',
              key: 'identityId',
              align: 'left',
              width: 100,
              resizable: true,
              sortable: 'custom',
              render: (h, params) => {
                let title = params.row['identityId']
                return h(
                  'div',
                  {
                    attrs: {
                      class: 'ivu-table-cell ivu-table-cell-ellipsis',
                      title: title
                    }
                  },
                  title
                )
              }
            },
            {
              title: '差标职级名称',
              key: 'positionLevelName',
              align: 'left',
              width: 150,
              resizable: true,
              sortable: 'custom',
              render: (h, params) => {
                let title = params.row['positionLevelName']
                return h(
                  'div',
                  {
                    attrs: {
                      class: 'ivu-table-cell ivu-table-cell-ellipsis',
                      title: title
                    }
                  },
                  title
                )
              }
            },
            {
              title: 'Base城市',
              key: 'baseCity',
              align: 'left',
              width: 100,
              resizable: true,
              sortable: 'custom',
              render: (h, params) => {
                let title = params.row['baseCity']
                return h(
                  'div',
                  {
                    attrs: {
                      class: 'ivu-table-cell ivu-table-cell-ellipsis',
                      title: title
                    }
                  },
                  title
                )
              }
            },
            {
              title: '员工类型',
              key: 'employeeType',
              width: 100,
              resizable: true,
              sortable: 'custom',
              render: (h, params) => {
                let text = params.row['employeeType']
                if (text == '0') {
                  text = '员工'
                } else if (text == '1') {
                  text = '因公客人'
                } else if (text == '2') {
                  text = '因私客人'
                }
                return h(
                  'div',
                  {
                    attrs: {
                      class: 'ivu-table-cell ivu-table-cell-ellipsis',
                      title: text
                    }
                  },
                  text
                )
              }
            },
            {
              title: '员工号',
              key: 'employeeId',
              width: 100,
              resizable: true,
              sortable: 'custom',
              render: (h, params) => {
                let text = params.row['employeeId']
                return h(
                  'div',
                  {
                    attrs: {
                      class: 'ivu-table-cell ivu-table-cell-ellipsis',
                      title: text
                    }
                  },
                  text
                )
              }
            },
            {
              title: '在职状态',
              align: 'center',
              key: 'workingState',
              width: 100,
              render: (h, params) => {
                return h(
                  'StatusButton',
                  {
                    // 修改StatusButton内容居中
                    style: {
                      'justify-content': 'center'
                    },
                    props: {
                      status: params.row.workingState == '1' ? '0' : '1'
                    }
                  },
                  params.row.workingState == '1' ? '在职' : '离职'
                )
              }
            },
            {
              title: '更新时间',
              key: 'updateTime',
              align: 'center',
              resizable: true,
              width: 160,
              render: (h, { row: { updateUser, updateTime } }) => {
                let txt = updateUser && updateTime ? `${updateTime}(${updateUser})` : ''
                return h(
                  'div',
                  {
                    attrs: {
                      class: 'ivu-table-cell ivu-table-cell-ellipsis',
                      title: txt
                    }
                  },
                  txt
                )
              }
            },
            {
              title: '创建时间',
              key: 'createTime',
              align: 'center',
              resizable: true,
              width: 220,
              render: (h, { row: { createUser, createTime } }) => {
                let txt = createUser && createTime ? `${createTime}(${createUser})` : ''
                return h(
                  'div',
                  {
                    attrs: {
                      class: 'ivu-table-cell ivu-table-cell-ellipsis',
                      title: txt
                    }
                  },
                  txt
                )
              }
            },
            {
              title: this.$t('common.operating'),
              align: 'left',
              fixed: 'right',
              resizable: true,
              width: 150,
              render: (h, { row }) => {
                let data = [{ text: '查看', handle: () => this.onOpenEditPage(row) }]
                // 提前创建防抖函数
                // if (row.enabled == '1') {
                //   data = [
                //     { text: '编辑', handle: () => this.onOpenEditPage(row) },
                //     { text: '禁用', handle: () => this.onUpdate(row, 0) }
                //   ]
                // } else {
                //   data = [
                //     { text: '编辑', handle: () => this.onOpenEditPage(row) },
                //     { text: '启用', handle: () => this.onUpdate(row, 1) },
                //     { text: '删除', handle: () => this.onDel(row) }
                //   ]
                // }
                // // 如果需要，可以在两个条件外都添加删除功能
                // if (!row.enabled || row.enabled === '0') {
                //   data.push({ text: '删除', handle: () => debouncedDelete(row) });
                // }

                return h('RowTools', {
                  props: {
                    data: data
                  }
                })
              }
            }
          ]
          if (!this.isPlatformAdmin) {
            columns = columns.filter(item => {
              if (item.key == 'tenantCode') {
                return false
              }
              return true
            })
          }
          return columns
        },
        autoFirst: false,
        rowClassNameFn: this.rowClassName // 自定义行样式
      }
    },
    userRolePermission() {
      if ($store.state['ripples-components'].resList) {
        return $util.checkPermission('ROLE_TYPE_USER')
      }
    },
    appRolePermission() {
      if ($store.state['ripples-components'].resList) {
        return $util.checkPermission('ROLE_TYPE_APP')
      }
    },
    tenantByName() {
      let tenantCodes = {}
      this.tenantList.map(item => {
        tenantCodes[item.tenantCode] = item.tenantName
      })
      return tenantCodes
    }
  },
  filters:{
 
  },
  created: function() {
    this.getStateSelect()
    this.tenantList = [];
    this.IdentityTypeArray  = [];
  },
  mounted() {
    console.log('identity :>> ', consta);
    this.IdentityTypeArray = consta.IdentityTypeArray
    this.init()
  },
  methods: {
    getIdentityType(val){ 
      // 1:身份证,2:公务护照,3:普通护照,4:港澳通行证,5:台胞证,6:回乡证,7:军人证,8:海员证,9:其他,10:台湾通行证,11.外国永久居留证,12.港澳台居民居住证
      if(+val && val <=0 ) return '';
      let arr = [
        '身份证',
        '公务护照',
        '普通护照',
        '港澳通行证',
        '台胞证',
        '回乡证',
        '军人证',
        '海员证',
        '其他',
        '台湾通行证',
        '外国永久居留证',
        '港澳台居民居住证',
      ]
      return arr[+val-1];
    },
    /**
     * 获取表格中选择的行ID
     */
    getSelectedIds() {
      let list = this.$refs['searchTable'].getSelectioned() || []
      let ids = []
      for (let u of list) {
        ids.push(u.id)
      }
      return ids
    },

    // 自定义行样式
    rowClassName(row) {
      //关联的菜单中是否存在有效的hasEnabledMenu:1-存在,0-不存在。enabled:1-有效，0-无效。roleType：1-用户角色，2-应用角色
      if (row.hasEnabledMenu == 0 && row.enabled == 1 && row.roleType == 1) {
        return 'tableDisableStyle'
      }
    },
    // 获取状态下拉数据
    async getStateSelect() {
      const [searchStatusList = []] = await Promise.all([valueSetAPI.getValueSetByCode('ENABLED_CODE')])
      this.searchStatusList = searchStatusList.filter(item => item.vsiKey !== 'ALL')
    },
    async init() {
      let { userInfo } = $store.state[CoreModuleName]
      if (!userInfo) return

      // 根据当前租户查询数据
      // this.searchForm.tenantCode = userInfo.tenantCode
      const [appData] = await Promise.all([
        // valueSetAPI.getValueSetByCode('ROLE_TYPE'),
        searchAppListByTenantCode({
          pageNum: 1,
          pageSize: 200,
          condition: {
            tenantCode: userInfo.tenantCode
          }
        })
      ])
      console.log('appData :>> ', appData)
      if (this.isPlatformAdmin) {
        // 平台管理员可以搜索租户信息
        this.$set(this.searchForm, 'tenantCode', '')
        /**
         * 加载所有租户
         */
        tenantAPI.queryTenantList().then(data => {
          // const {tenantName ,tenantCode,id }
          this.tenantList = data
        })
      }
      // 查询列表
      this.search()
    },

    search(page = 1) {
      let searchParams = Object.assign({}, this.searchForm)
      this.$refs['searchTable'].load(searchParams, page)
    },
    reset() {
      this.$refs['searchForm'].resetFields()
      this.search(1)
    },
    onUpdate: debounce(function(row, enabled)  {
      let title = enabled == 1 ? '启用' : '禁用'
      new $confirm('您确定要' + title + '该行差标数据吗？', this).then(() => {
        // enabled 0 禁用
        apiTripAccountBatchOperate({ ids: row.id + '', enabled: enabled + '' })
          .then(res => {
            this.$message.success({
              content: '修改成功',
              duration: 3
            })
            this.search()
          })
          .catch(data => {
            this.$message.error({
              content: data.message,
              duration: 3
            })
          })
      })
    }, 300),
    onDel: debounce(function(row){
      new $confirm('您确定要删除该行差标数据吗？', this).then(() => {
        apiTripAccountBatchOperate({ ids: row.id + '', enabled: '2' })
          .then(res => {
            this.$message.success({
              content: this.$t('module.orgManage.deleteSuccess'),
              duration: 3
            })
            this.search()
          })
          .catch(data => {
            this.$message.error({
              content: data.message,
              duration: 3
            })
          })
      })
    }, 300),
    onOpenEditPage: debounce(function(row){
      new this.$sidelipPage(
        () => import('./openCardDetail.vue'),
        {
          props: {
            crtripId: row.crtripId,
            userTenantCode:row.tenantCode,
            tenantByName:this.tenantByName,
            disabled:true,
          },
          isActionTop: false
        },
        data => {
          data && this.search()
        }
      )
    }, 300),
    onOpenAddPage: debounce(function() {
      new this.$sidelipPage(
        () => import('./openCardDetail.vue'),
        {
          props: {},
          isActionTop: false
        },
        data => {
          data && this.search()
        }
      )
      //   new this.$pageModal(
      //     () => import('./openCardDetail.vue'),
      //     {
      //       props: {
      //         tenantCode: this.searchForm.tenantCode
      //       }
      //     },
      //     data => {
      //       data && this.search()
      //     }
      //   )
    }, 300),

    getDateString(DateStr) {
      if (!DateStr) {
        return ''
      }
      const dateParts = DateStr.split(' ')[0]
        .split('-')
        .map(part => (part < 10 ? '0' + part : part))
      return dateParts.join('-')
    },
    queryListByPage({ responseProcess, param }) {
      return apiTripAccountQueryPage(param)
        .then(data => {
          console.log('data :>> ', data);
         
          if (data.success) {
                      responseProcess(data.data)
          } else {
            this.$message.error({
              content: data.message || '未查询到信息',
              duration: 3
            })
            responseProcess({ records: [] })
          }
        })
        .catch(error => {
          console.error('查询差标信息失败:', error)
          this.$message.error({
            content: error.message,
            duration: 3
          })
          responseProcess({ records: [] })
        })
    }
  }
}
</script>

<style></style>
